import { defineStore } from "pinia";
import { ref } from "vue";
import { computed } from "vue";
import { useUserStore } from "./userStore";
import {deleteCartApi,insertCartApi,findNewCartListApi} from "@/api/cart";

export const useCartStore = defineStore('cart', () => {
  const userStore = useUserStore()
  const isLogin = computed(() => userStore.userInfo.token)
  const cartList = ref([]);

  const updateCartList =async ()=>{
    const res = await findNewCartListApi()
    cartList.value = res.result
  }
  const addCart = async (goods) => {
        //添加操作
        if(isLogin.value){
         await insertCartApi(goods)
         updateCartList()
        }else{
          const item = cartList.value.find((item) => goods.skuId === item.skuId)
          if(item){
            item.count += goods.count
          }else{
          cartList.value.push(goods)
          }
        }
        }
  const delCart = async (skuId)=>{
    if(isLogin.value){
     await deleteCartApi([skuId])
     updateCartList()
    }else{
      cartList.value = cartList.value.filter((item)=>{
        return item.skuId!== skuId
       })
    }
  }
const clearCart = ()=>{
  cartList.value = []
}
  //计算属性
const allCount = computed(()=>cartList.value.reduce((a,c)=>a + c.count,0))
const allPrice = computed(()=>cartList.value.reduce((a,c)=>a + c.count * c.price,0))

const selectedCount = computed(()=>cartList.value.filter((item)=>item.selected).reduce((a,c)=>a + c.count,0))
const selectedPrice = computed(()=>cartList.value.filter((item)=>item.selected).reduce((a,c)=>a + c.count * c.price,0))

const singleCheck = (skuId,selected) =>{
const item = cartList.value.find((item)=> item.skuId === skuId)
item.selected = selected
}

const allCheck=(selected)=>{
cartList.value.forEach((item)=>{item.selected = selected})
}
const isAll = computed(()=>cartList.value.every((item)=>item.selected))

  return {
    cartList,
    addCart,
    delCart,
    allCount,
    allPrice,
    singleCheck,
    allCheck,
    isAll,
    selectedCount,
    selectedPrice,
    clearCart,
    updateCartList
  }
},{
  persist: true,
})
